package cn.net.yugu.doraemon.common.util;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * @author xiangzr
 * @version 2023/5/11 20:23:12
 */
public class BooleanOptional {

    private final Optional<Boolean> value;


    private BooleanOptional(Boolean value) {
        this.value = Optional.of(value);
    }

    private BooleanOptional(Supplier<Boolean> booleanSupplier) {
        this(Objects.requireNonNull(booleanSupplier, "supplier require non null!").get());
    }

    public static BooleanOptional of(Boolean b) {
        return new BooleanOptional(b == null ? false : b);
    }

    public static BooleanOptional of(Supplier<Boolean> supplier) {
        return new BooleanOptional(supplier);
    }

    public void ifTrue(Runnable runnable) {
        value.filter(Objects::nonNull)
                .filter(b -> b)
                .ifPresent(aBoolean -> {
                    runnable.run();
                });
    }
}
